﻿using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Data;
using System.Web;
using Enterprise.Exceptions;

namespace Enterprise.Modules
{

    /// <summary>
    /// Contains controlstuff for ModuleController
    /// </summary>
    public abstract class ModuleAdminControls : UserControl
    {
        /// <summary>
        /// Controls the up and down buttons for each module in a region.
        /// </summary>
        /// <param name="dir">Direction to move a module</param>
        /// <param name="regionID">The region id</param>
        /// <param name="pageID">the current pageid</param>
        /// <param name="moduleID">The current moduleid</param>
        public void Move(Direction dir, string regionID, string pageID, string moduleID)
        {
            try
            {
                int sortOrder = -2, newSortOrder = -2;
                SqlConnection Conn = new SqlConnection(Config.ConnectionString());

                string sql = string.Format("SELECT * FROM Objects WHERE id={0}", moduleID);

                SqlCommand cmd = new SqlCommand(sql, Conn);
                Conn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                    sortOrder = Convert.ToInt32(dr["sortOrder"]);

                Conn.Close();

                newSortOrder = sortOrder;

                if (dir == Direction.UP)
                    newSortOrder -= 1;
                else
                    newSortOrder += 1;

                if (sortOrder != -2)
                {
                    cmd = new SqlCommand("ReorderPosition", Conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@New", SqlDbType.Int).Value = newSortOrder;
                    cmd.Parameters.Add("@Old", SqlDbType.Int).Value = sortOrder;
                    cmd.Parameters.Add("@PageID", SqlDbType.Int).Value = pageID;
                    cmd.Parameters.Add("@RegionID", SqlDbType.VarChar).Value = regionID;
 
                    Conn.Open();
                    cmd.ExecuteNonQuery();
                    Conn.Close(); 

                }
                Response.Redirect(Request.RawUrl);
            }
            catch (Exception ex) { throw new Exception(ex.ToString()); } 
        }
    }
}
